/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.config.console.endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.boot.actuate.endpoint.web.WebEndpointResponse;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 控制台刷新端点
 *
 * @author ebert_chan
 */
@Endpoint(id = "console-refresh")
public class ConsoleRefreshEndpoint implements ApplicationContextAware {

    private static final Logger log = LoggerFactory.getLogger(ConsoleRefreshEndpoint.class);

    private ApplicationContext applicationContext;

    private AtomicBoolean running = new AtomicBoolean(false);

    @ReadOperation
    public WebEndpointResponse<String> refresh() {
        if (!running.compareAndSet(false, true)) {
            return new WebEndpointResponse<>("running", WebEndpointResponse.STATUS_OK);
        }

        try {
            log.info("Received console refresh event.");

            applicationContext.publishEvent(new RefreshEvent(this, null, "Refresh console config"));

        } finally {
            running.compareAndSet(true, false);
        }


        return new WebEndpointResponse<>("refreshed", WebEndpointResponse.STATUS_OK);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
